package com.cskaoyan.servlet;


import com.cskaoyan.bean.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.model.MarketOrder;
import com.cskaoyan.service.CommentService;
import com.cskaoyan.service.LogService;
import com.cskaoyan.service.impl.CommentServiceImpl;
import com.cskaoyan.service.impl.LogServiceImpl;
import com.cskaoyan.service.OrderService;
import com.cskaoyan.service.impl.OrderServiceImpl;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.JacksonUtil;
import com.cskaoyan.utils.MyBatisUtil;
import com.cskaoyan.utils.TransactionUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;


@WebServlet("/admin/order/*")
public class AdminOrderServlet extends CommonServlet {
    OrderService orderService = new OrderServiceImpl();
    LogService logService = new LogServiceImpl();
    CommentService commentService = new CommentServiceImpl();

    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException, InvocationTargetException, IllegalAccessException {
        OrderListParameter parameter = new OrderListParameter();
        Map<String, String[]> parameterMap = request.getParameterMap();
        BeanUtils.copyProperties(parameter, parameterMap);
        PageData data = orderService.list(parameter);
        return BaseRespVo.ok(data);
    }

    public BaseRespVo detail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int orderId = Integer.parseInt(id);
        OrderDetailData orderDetailData = orderService.selectById(orderId);
        return BaseRespVo.ok(orderDetailData);
    }

    public BaseRespVo refund(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TransactionUtil.startTransaction();
        String jsonStr = request.getReader().readLine();
        OrderRefundParameter orderRefundParameter = JacksonUtil.read(jsonStr, OrderRefundParameter.class);
        String orderSn = orderService.refund(orderRefundParameter.getOrderId(), orderRefundParameter.getRefundMoney());
        logService.insertLog(request, 2, "退款", true, "订单编号 " + orderSn, "");
        TransactionUtil.commit();
        return BaseRespVo.ok(null);
    }

    public BaseRespVo channel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Map<String, String>> vendors = (List<Map<String, String>>) getServletContext().getAttribute(Constant.VENDORS);
        return BaseRespVo.ok(vendors);
    }

    public BaseRespVo ship(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TransactionUtil.startTransaction();
        MarketOrderMapper orderMapper = TransactionUtil.getMapper(MarketOrderMapper.class);
        String jsonStr = request.getReader().readLine();
        OrderShipParameter shipParameter = JacksonUtil.read(jsonStr, OrderShipParameter.class);
        MarketOrder order = orderMapper.selectByPrimaryKey(shipParameter.getOrderId());
        if ((shipParameter.getShipSn() == null || shipParameter.getShipSn().isEmpty()) || (shipParameter.getShipChannel() == null || shipParameter.getShipChannel().isEmpty())) {
            logService.insertLog(request, 2, "发货", false, "失败，参数不对 订单编号 " + order.getOrderSn(), "");
            TransactionUtil.commit();
            return BaseRespVo.fail("参数不对", 401);
        }
        String orderSn = orderService.ship(shipParameter);
        logService.insertLog(request, 2, "发货", true, "订单编号 " + orderSn, "");
        TransactionUtil.commit();
        return BaseRespVo.ok(null);
    }

    public BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        String jsonStr = request.getReader().readLine();
        Map map = JacksonUtil.read(jsonStr, Map.class);
        Object orderId = map.get("orderId");
        MarketOrderMapper orderMapper = sqlSession.getMapper(MarketOrderMapper.class);
        MarketOrder order = orderMapper.selectByPrimaryKey((Integer) orderId);

        Short[] statusArr = {102, 103, 203, 401, 402};
        boolean result = Arrays.stream(statusArr).noneMatch(status -> Objects.equals(status, order.getOrderStatus()));
        if (result) {
            logService.insertLog(request, 2, "删除", false, "失败，订单不能删除 订单编号 " + order.getOrderSn(), "");
            TransactionUtil.commit();
            return BaseRespVo.fail("订单不能删除", 623);
        }
        orderService.delete((Integer) orderId);
        logService.insertLog(request, 2, "删除", true, "订单编号 " + order.getOrderSn(), "");
        TransactionUtil.commit();
        return BaseRespVo.ok(null);
    }

    public BaseRespVo reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        HashMap hashMap = JacksonUtil.read(jsonStr, HashMap.class);
        Boolean result = commentService.reply(hashMap);
        //根据传回来的值进行判断
        if (result) {
            return BaseRespVo.ok(null);
        } else {
            return BaseRespVo.fail("订单商品已回复！", 622);
        }
    }
}
